package com.MoveEat.views;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.MoveEat.R;
import com.MoveEat.Utils.Consts;
import com.MoveEat.Utils.FacebookLoginHelper;
import com.MoveEat.Utils.Utils;
import com.MoveEat.items.CommentDataType;
import com.google.gson.Gson;

public class CommentDialog extends Dialog
{

	private int					mMEUID;
	private ProgressBar			mProgBar;
	private EditText			mEditText;
	private CommentsListAdapter	adapter;
	private Context				mContext;
	private ListView			mCommentsListView;
	private Button				mSendBtn;
	private Activity			mActivity;

	public CommentDialog(Context context, boolean cancelable, OnCancelListener cancelListener)
	{
		super(context, cancelable, cancelListener);
	}

	public CommentDialog(Context context, int theme)
	{
		super(context, theme);
	}

	public CommentDialog(Context context)
	{
		super(context);
	}

	public CommentDialog(Context context, int meUID, String restName, final long mRestId, Activity act)
	{
		super(context);
		mContext = context;
		mActivity = act;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
		if (meUID == -1)
		{
			mMEUID = FacebookLoginHelper.getInstance(getOwnerActivity()).getMoveEatUID();
		}
		else
		{
			mMEUID = meUID;
		}
		setContentView(R.layout.comment_dialog_layout);
		getWindow().setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		LinearLayout linear = (LinearLayout) findViewById(R.id.linear_parent);
		TextView restText = new TextView(context);
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		layoutParams.gravity = Gravity.CENTER;
		restText.setLayoutParams(layoutParams);
		restText.setText(restName);
		restText.setTextColor(R.color.black);
		restText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
		linear.addView(restText, 0);
		mSendBtn = (Button) findViewById(R.id.send_button);
		mSendBtn.setEnabled(false);
		Button returnBtn = (Button) findViewById(R.id.return_button);
		mEditText = (EditText) findViewById(R.id.comment_text);
		mEditText.addTextChangedListener(new TextWatcher()
		{

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
				if (!TextUtils.isEmpty(s))
				{
					mSendBtn.setEnabled(true);
				}
				else
				{
					mSendBtn.setEnabled(false);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after)
			{
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s)
			{
				if (!TextUtils.isEmpty(s))
				{
					mSendBtn.setEnabled(true);
				}
				else
				{
					mSendBtn.setEnabled(false);
				}

			}
		});
		mProgBar = (ProgressBar) findViewById(R.id.prog_bar);

		mCommentsListView = (ListView) findViewById(R.id.comment_list);
		new AsyncTask<Void, Void, String>()
		{
			@Override
			protected void onPreExecute()
			{
				mProgBar.setVisibility(View.VISIBLE);
			}

			@Override
			protected String doInBackground(Void... params)
			{
				return Utils.preformRequest(Utils.BASE_URL + "comments.php?rest_id=" + mRestId);
			}

			@Override
			protected void onPostExecute(String res)
			{
				try
				{
					JSONObject obj = new JSONObject(res);
					JSONArray arr = obj.optJSONArray("comments");
					ArrayList<CommentType> commentsListArray = new ArrayList<CommentDialog.CommentType>();
					for (int i = 0; i < arr.length(); i++)
					{
						commentsListArray.add(new CommentType(arr.optJSONObject(i), mContext));
					}
					adapter = new CommentsListAdapter(commentsListArray);
					mCommentsListView.setAdapter(adapter);
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}

				mProgBar.setVisibility(View.GONE);
				Utils.log(2,res);
			}

		}.execute();

		mSendBtn.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mActivity.getApplicationContext());
				mMEUID = prefs.getInt(Consts.Extras.ME_UID, -1);
				if (mMEUID <= 0)
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
					builder.setCancelable(true).setMessage(R.string.cant_comment);
					builder.setNegativeButton(R.string.back, new OnClickListener()
					{

						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							dialog.dismiss();
						}
					});
					builder.setPositiveButton(R.string.sign_in, new OnClickListener()
					{

						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							FacebookLoginHelper.getInstance(mActivity).facebookSignIn(mActivity);
							dialog.dismiss();
						}
					});
					AlertDialog alertDialog = builder.create();
					alertDialog.getWindow().addFlags(Window.FEATURE_NO_TITLE);
					alertDialog.show();
				}
				else
				{

					new AsyncTask<Void, Void, String>()
					{

						@Override
						protected void onPreExecute()
						{
							mProgBar.setVisibility(View.VISIBLE);
						}

						@Override
						protected String doInBackground(Void... arg0)
						{
							String name = FacebookLoginHelper.getInstance(getOwnerActivity()).getName();
							Utils.log(2,"name is:" + name);
							CommentDataType comment = new CommentDataType((int) mRestId, name, mEditText.getText().toString(), mMEUID);
							Gson gson = new Gson();

							String json = gson.toJson(comment);
							Utils.log(2,"Sending in payload:" + json);
							Utils.preformPostRequest(Utils.BASE_URL + "comments.php", json);
							return Utils.preformRequest(Utils.BASE_URL + "comments.php?rest_id=" + mRestId);
						}

						@Override
						protected void onPostExecute(String res)
						{
							try
							{
								JSONObject obj = new JSONObject(res);
								JSONArray arr = obj.optJSONArray("comments");
								ArrayList<CommentType> commentsListArray = new ArrayList<CommentDialog.CommentType>();
								for (int i = 0; i < arr.length(); i++)
								{
									commentsListArray.add(new CommentType(arr.optJSONObject(i), mContext));
								}
								adapter.updateList(commentsListArray);
								mCommentsListView.invalidate();
							}
							catch (JSONException e)
							{
								e.printStackTrace();
								mProgBar.setVisibility(View.GONE);
							}
							mEditText.setText("");
							mProgBar.setVisibility(View.GONE);
							Utils.log(2,res);
						}

					}.execute();
				}
			}
		});

		returnBtn.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				CommentDialog.this.dismiss();
			}
		});

	}

	private class CommentsListAdapter extends BaseAdapter
	{

		ArrayList<CommentType>	mList;

		public CommentsListAdapter(ArrayList<CommentType> list)
		{
			mList = list;
		}

		@Override
		public int getCount()
		{
			return mList.size();
		}

		@Override
		public Object getItem(int pos)
		{
			return mList.get(pos);
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		public void updateList(ArrayList<CommentType> list)
		{
			mList = list;
			notifyDataSetChanged();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			final ViewHolder holder;
			CommentType currentComment = mList.get(position);
			if (convertView == null)
			{
				holder = new ViewHolder();
				LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = vi.inflate(R.layout.rest_comment_layout, null);
				holder.mName = (TextView) convertView.findViewById(R.id.commenter_name);
				holder.mComment = (TextView) convertView.findViewById(R.id.comment);
				holder.mDate = (TextView) convertView.findViewById(R.id.comment_time);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			holder.mName.setText(currentComment.getName());
			holder.mComment.setText(currentComment.getComment());
			holder.mDate.setText(currentComment.getDate());

			return convertView;
		}
	}

	static class ViewHolder
	{
		TextView	mName;
		TextView	mComment;
		TextView	mDate;
	}

	private class CommentType
	{

		private String	mName;
		private String	mComment;
		private String	mDate;

		public CommentType(JSONObject obj, Context context)
		{

			mName = obj.optString("AUTHOR");
			mComment = obj.optString("FEEDBACK_TEXT");
			mDate = obj.optString("DATE_ADDED");
		}

		public String getName()
		{
			return mName;
		}

		public String getComment()
		{
			return mComment;
		}

		public String getDate()
		{
			return mDate;
		}

	}

}
